{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "cWSEUWaF55Fg",
        "outputId": "ca9f39e0-40dd-49b4-b324-f67b11242cd2"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Collecting pymongo==4.7.2\n",
            "  Using cached pymongo-4.7.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (670 kB)\n",
            "Collecting crewai==0.22.5\n",
            "  Using cached crewai-0.22.5-py3-none-any.whl (51 kB)\n",
            "Collecting langchain==0.1.10\n",
            "  Using cached langchain-0.1.10-py3-none-any.whl (806 kB)\n",
            "Collecting langchain-community\n",
            "  Downloading langchain_community-0.2.5-py3-none-any.whl (2.2 MB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.2/2.2 MB\u001b[0m \u001b[31m8.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hCollecting langchain-openai==0.0.5\n",
            "  Using cached langchain_openai-0.0.5-py3-none-any.whl (29 kB)\n",
            "Collecting duckduckgo-search==6.1.5\n",
            "  Using cached duckduckgo_search-6.1.5-py3-none-any.whl (24 kB)\n",
            "Collecting dnspython<3.0.0,>=1.16.0 (from pymongo==4.7.2)\n",
            "  Using cached dnspython-2.6.1-py3-none-any.whl (307 kB)\n",
            "Requirement already satisfied: click<9.0.0,>=8.1.7 in /usr/local/lib/python3.10/dist-packages (from crewai==0.22.5) (8.1.7)\n",
            "Collecting instructor<0.6.0,>=0.5.2 (from crewai==0.22.5)\n",
            "  Using cached instructor-0.5.2-py3-none-any.whl (33 kB)\n",
            "Collecting openai<2.0.0,>=1.13.3 (from crewai==0.22.5)\n",
            "  Using cached openai-1.34.0-py3-none-any.whl (325 kB)\n",
            "Collecting opentelemetry-api<2.0.0,>=1.22.0 (from crewai==0.22.5)\n",
            "  Using cached opentelemetry_api-1.25.0-py3-none-any.whl (59 kB)\n",
            "Collecting opentelemetry-exporter-otlp-proto-http<2.0.0,>=1.22.0 (from crewai==0.22.5)\n",
            "  Using cached opentelemetry_exporter_otlp_proto_http-1.25.0-py3-none-any.whl (16 kB)\n",
            "Collecting opentelemetry-sdk<2.0.0,>=1.22.0 (from crewai==0.22.5)\n",
            "  Using cached opentelemetry_sdk-1.25.0-py3-none-any.whl (107 kB)\n",
            "Requirement already satisfied: pydantic<3.0.0,>=2.4.2 in /usr/local/lib/python3.10/dist-packages (from crewai==0.22.5) (2.7.3)\n",
            "Collecting python-dotenv==1.0.0 (from crewai==0.22.5)\n",
            "  Using cached python_dotenv-1.0.0-py3-none-any.whl (19 kB)\n",
            "Collecting regex<2024.0.0,>=2023.12.25 (from crewai==0.22.5)\n",
            "  Using cached regex-2023.12.25-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (773 kB)\n",
            "Requirement already satisfied: PyYAML>=5.3 in /usr/local/lib/python3.10/dist-packages (from langchain==0.1.10) (6.0.1)\n",
            "Requirement already satisfied: SQLAlchemy<3,>=1.4 in /usr/local/lib/python3.10/dist-packages (from langchain==0.1.10) (2.0.30)\n",
            "Requirement already satisfied: aiohttp<4.0.0,>=3.8.3 in /usr/local/lib/python3.10/dist-packages (from langchain==0.1.10) (3.9.5)\n",
            "Requirement already satisfied: async-timeout<5.0.0,>=4.0.0 in /usr/local/lib/python3.10/dist-packages (from langchain==0.1.10) (4.0.3)\n",
            "Collecting dataclasses-json<0.7,>=0.5.7 (from langchain==0.1.10)\n",
            "  Using cached dataclasses_json-0.6.7-py3-none-any.whl (28 kB)\n",
            "Collecting jsonpatch<2.0,>=1.33 (from langchain==0.1.10)\n",
            "  Using cached jsonpatch-1.33-py2.py3-none-any.whl (12 kB)\n",
            "Collecting langchain-community\n",
            "  Downloading langchain_community-0.0.38-py3-none-any.whl (2.0 MB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.0/2.0 MB\u001b[0m \u001b[31m57.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hCollecting langchain-core<0.2,>=0.1.28 (from langchain==0.1.10)\n",
            "  Downloading langchain_core-0.1.52-py3-none-any.whl (302 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m302.9/302.9 kB\u001b[0m \u001b[31m27.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hCollecting langchain-text-splitters<0.1,>=0.0.1 (from langchain==0.1.10)\n",
            "  Downloading langchain_text_splitters-0.0.2-py3-none-any.whl (23 kB)\n",
            "Collecting langsmith<0.2.0,>=0.1.0 (from langchain==0.1.10)\n",
            "  Downloading langsmith-0.1.80-py3-none-any.whl (125 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m125.3/125.3 kB\u001b[0m \u001b[31m14.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hRequirement already satisfied: numpy<2,>=1 in /usr/local/lib/python3.10/dist-packages (from langchain==0.1.10) (1.25.2)\n",
            "Requirement already satisfied: requests<3,>=2 in /usr/local/lib/python3.10/dist-packages (from langchain==0.1.10) (2.31.0)\n",
            "Requirement already satisfied: tenacity<9.0.0,>=8.1.0 in /usr/local/lib/python3.10/dist-packages (from langchain==0.1.10) (8.3.0)\n",
            "Collecting tiktoken<0.6.0,>=0.5.2 (from langchain-openai==0.0.5)\n",
            "  Downloading tiktoken-0.5.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.0 MB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.0/2.0 MB\u001b[0m \u001b[31m38.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hCollecting pyreqwest-impersonate>=0.4.7 (from duckduckgo-search==6.1.5)\n",
            "  Downloading pyreqwest_impersonate-0.4.8-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.7 MB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.7/2.7 MB\u001b[0m \u001b[31m44.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hCollecting orjson>=3.10.3 (from duckduckgo-search==6.1.5)\n",
            "  Downloading orjson-3.10.5-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (144 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m145.0/145.0 kB\u001b[0m \u001b[31m7.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hRequirement already satisfied: aiosignal>=1.1.2 in /usr/local/lib/python3.10/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain==0.1.10) (1.3.1)\n",
            "Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain==0.1.10) (23.2.0)\n",
            "Requirement already satisfied: frozenlist>=1.1.1 in /usr/local/lib/python3.10/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain==0.1.10) (1.4.1)\n",
            "Requirement already satisfied: multidict<7.0,>=4.5 in /usr/local/lib/python3.10/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain==0.1.10) (6.0.5)\n",
            "Requirement already satisfied: yarl<2.0,>=1.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain==0.1.10) (1.9.4)\n",
            "Collecting marshmallow<4.0.0,>=3.18.0 (from dataclasses-json<0.7,>=0.5.7->langchain==0.1.10)\n",
            "  Downloading marshmallow-3.21.3-py3-none-any.whl (49 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m49.2/49.2 kB\u001b[0m \u001b[31m5.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hCollecting typing-inspect<1,>=0.4.0 (from dataclasses-json<0.7,>=0.5.7->langchain==0.1.10)\n",
            "  Downloading typing_inspect-0.9.0-py3-none-any.whl (8.8 kB)\n",
            "Collecting docstring-parser<0.16,>=0.15 (from instructor<0.6.0,>=0.5.2->crewai==0.22.5)\n",
            "  Downloading docstring_parser-0.15-py3-none-any.whl (36 kB)\n",
            "Requirement already satisfied: rich<14.0.0,>=13.7.0 in /usr/local/lib/python3.10/dist-packages (from instructor<0.6.0,>=0.5.2->crewai==0.22.5) (13.7.1)\n",
            "Collecting typer<0.10.0,>=0.9.0 (from instructor<0.6.0,>=0.5.2->crewai==0.22.5)\n",
            "  Downloading typer-0.9.4-py3-none-any.whl (45 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m46.0/46.0 kB\u001b[0m \u001b[31m5.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hCollecting jsonpointer>=1.9 (from jsonpatch<2.0,>=1.33->langchain==0.1.10)\n",
            "  Downloading jsonpointer-3.0.0-py2.py3-none-any.whl (7.6 kB)\n",
            "Collecting packaging<24.0,>=23.2 (from langchain-core<0.2,>=0.1.28->langchain==0.1.10)\n",
            "  Downloading packaging-23.2-py3-none-any.whl (53 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m53.0/53.0 kB\u001b[0m \u001b[31m6.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hRequirement already satisfied: anyio<5,>=3.5.0 in /usr/local/lib/python3.10/dist-packages (from openai<2.0.0,>=1.13.3->crewai==0.22.5) (3.7.1)\n",
            "Requirement already satisfied: distro<2,>=1.7.0 in /usr/lib/python3/dist-packages (from openai<2.0.0,>=1.13.3->crewai==0.22.5) (1.7.0)\n",
            "Collecting httpx<1,>=0.23.0 (from openai<2.0.0,>=1.13.3->crewai==0.22.5)\n",
            "  Downloading httpx-0.27.0-py3-none-any.whl (75 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m75.6/75.6 kB\u001b[0m \u001b[31m9.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hRequirement already satisfied: sniffio in /usr/local/lib/python3.10/dist-packages (from openai<2.0.0,>=1.13.3->crewai==0.22.5) (1.3.1)\n",
            "Requirement already satisfied: tqdm>4 in /usr/local/lib/python3.10/dist-packages (from openai<2.0.0,>=1.13.3->crewai==0.22.5) (4.66.4)\n",
            "Requirement already satisfied: typing-extensions<5,>=4.7 in /usr/local/lib/python3.10/dist-packages (from openai<2.0.0,>=1.13.3->crewai==0.22.5) (4.12.2)\n",
            "Collecting deprecated>=1.2.6 (from opentelemetry-api<2.0.0,>=1.22.0->crewai==0.22.5)\n",
            "  Downloading Deprecated-1.2.14-py2.py3-none-any.whl (9.6 kB)\n",
            "Requirement already satisfied: importlib-metadata<=7.1,>=6.0 in /usr/local/lib/python3.10/dist-packages (from opentelemetry-api<2.0.0,>=1.22.0->crewai==0.22.5) (7.1.0)\n",
            "Requirement already satisfied: googleapis-common-protos~=1.52 in /usr/local/lib/python3.10/dist-packages (from opentelemetry-exporter-otlp-proto-http<2.0.0,>=1.22.0->crewai==0.22.5) (1.63.1)\n",
            "Collecting opentelemetry-exporter-otlp-proto-common==1.25.0 (from opentelemetry-exporter-otlp-proto-http<2.0.0,>=1.22.0->crewai==0.22.5)\n",
            "  Downloading opentelemetry_exporter_otlp_proto_common-1.25.0-py3-none-any.whl (17 kB)\n",
            "Collecting opentelemetry-proto==1.25.0 (from opentelemetry-exporter-otlp-proto-http<2.0.0,>=1.22.0->crewai==0.22.5)\n",
            "  Downloading opentelemetry_proto-1.25.0-py3-none-any.whl (52 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m52.5/52.5 kB\u001b[0m \u001b[31m6.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hRequirement already satisfied: protobuf<5.0,>=3.19 in /usr/local/lib/python3.10/dist-packages (from opentelemetry-proto==1.25.0->opentelemetry-exporter-otlp-proto-http<2.0.0,>=1.22.0->crewai==0.22.5) (3.20.3)\n",
            "Collecting opentelemetry-semantic-conventions==0.46b0 (from opentelemetry-sdk<2.0.0,>=1.22.0->crewai==0.22.5)\n",
            "  Downloading opentelemetry_semantic_conventions-0.46b0-py3-none-any.whl (130 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m130.5/130.5 kB\u001b[0m \u001b[31m11.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hRequirement already satisfied: annotated-types>=0.4.0 in /usr/local/lib/python3.10/dist-packages (from pydantic<3.0.0,>=2.4.2->crewai==0.22.5) (0.7.0)\n",
            "Requirement already satisfied: pydantic-core==2.18.4 in /usr/local/lib/python3.10/dist-packages (from pydantic<3.0.0,>=2.4.2->crewai==0.22.5) (2.18.4)\n",
            "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests<3,>=2->langchain==0.1.10) (3.3.2)\n",
            "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests<3,>=2->langchain==0.1.10) (3.7)\n",
            "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests<3,>=2->langchain==0.1.10) (2.0.7)\n",
            "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests<3,>=2->langchain==0.1.10) (2024.6.2)\n",
            "Requirement already satisfied: greenlet!=0.4.17 in /usr/local/lib/python3.10/dist-packages (from SQLAlchemy<3,>=1.4->langchain==0.1.10) (3.0.3)\n",
            "Requirement already satisfied: exceptiongroup in /usr/local/lib/python3.10/dist-packages (from anyio<5,>=3.5.0->openai<2.0.0,>=1.13.3->crewai==0.22.5) (1.2.1)\n",
            "Requirement already satisfied: wrapt<2,>=1.10 in /usr/local/lib/python3.10/dist-packages (from deprecated>=1.2.6->opentelemetry-api<2.0.0,>=1.22.0->crewai==0.22.5) (1.14.1)\n",
            "Collecting httpcore==1.* (from httpx<1,>=0.23.0->openai<2.0.0,>=1.13.3->crewai==0.22.5)\n",
            "  Downloading httpcore-1.0.5-py3-none-any.whl (77 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m77.9/77.9 kB\u001b[0m \u001b[31m8.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hCollecting h11<0.15,>=0.13 (from httpcore==1.*->httpx<1,>=0.23.0->openai<2.0.0,>=1.13.3->crewai==0.22.5)\n",
            "  Downloading h11-0.14.0-py3-none-any.whl (58 kB)\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m58.3/58.3 kB\u001b[0m \u001b[31m7.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25hRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.10/dist-packages (from importlib-metadata<=7.1,>=6.0->opentelemetry-api<2.0.0,>=1.22.0->crewai==0.22.5) (3.19.2)\n",
            "Requirement already satisfied: markdown-it-py>=2.2.0 in /usr/local/lib/python3.10/dist-packages (from rich<14.0.0,>=13.7.0->instructor<0.6.0,>=0.5.2->crewai==0.22.5) (3.0.0)\n",
            "Requirement already satisfied: pygments<3.0.0,>=2.13.0 in /usr/local/lib/python3.10/dist-packages (from rich<14.0.0,>=13.7.0->instructor<0.6.0,>=0.5.2->crewai==0.22.5) (2.16.1)\n",
            "Collecting mypy-extensions>=0.3.0 (from typing-inspect<1,>=0.4.0->dataclasses-json<0.7,>=0.5.7->langchain==0.1.10)\n",
            "  Downloading mypy_extensions-1.0.0-py3-none-any.whl (4.7 kB)\n",
            "Requirement already satisfied: mdurl~=0.1 in /usr/local/lib/python3.10/dist-packages (from markdown-it-py>=2.2.0->rich<14.0.0,>=13.7.0->instructor<0.6.0,>=0.5.2->crewai==0.22.5) (0.1.2)\n",
            "Installing collected packages: typer, regex, python-dotenv, pyreqwest-impersonate, packaging, orjson, opentelemetry-proto, mypy-extensions, jsonpointer, h11, docstring-parser, dnspython, deprecated, typing-inspect, tiktoken, pymongo, opentelemetry-exporter-otlp-proto-common, opentelemetry-api, marshmallow, jsonpatch, httpcore, duckduckgo-search, opentelemetry-semantic-conventions, langsmith, httpx, dataclasses-json, opentelemetry-sdk, openai, langchain-core, opentelemetry-exporter-otlp-proto-http, langchain-text-splitters, langchain-openai, langchain-community, instructor, langchain, crewai\n",
            "  Attempting uninstall: typer\n",
            "    Found existing installation: typer 0.12.3\n",
            "    Uninstalling typer-0.12.3:\n",
            "      Successfully uninstalled typer-0.12.3\n",
            "  Attempting uninstall: regex\n",
            "    Found existing installation: regex 2024.5.15\n",
            "    Uninstalling regex-2024.5.15:\n",
            "      Successfully uninstalled regex-2024.5.15\n",
            "  Attempting uninstall: packaging\n",
            "    Found existing installation: packaging 24.1\n",
            "    Uninstalling packaging-24.1:\n",
            "      Successfully uninstalled packaging-24.1\n",
            "  Attempting uninstall: docstring-parser\n",
            "    Found existing installation: docstring_parser 0.16\n",
            "    Uninstalling docstring_parser-0.16:\n",
            "      Successfully uninstalled docstring_parser-0.16\n",
            "Successfully installed crewai-0.22.5 dataclasses-json-0.6.7 deprecated-1.2.14 dnspython-2.6.1 docstring-parser-0.15 duckduckgo-search-6.1.5 h11-0.14.0 httpcore-1.0.5 httpx-0.27.0 instructor-0.5.2 jsonpatch-1.33 jsonpointer-3.0.0 langchain-0.1.10 langchain-community-0.0.38 langchain-core-0.1.52 langchain-openai-0.0.5 langchain-text-splitters-0.0.2 langsmith-0.1.80 marshmallow-3.21.3 mypy-extensions-1.0.0 openai-1.34.0 opentelemetry-api-1.25.0 opentelemetry-exporter-otlp-proto-common-1.25.0 opentelemetry-exporter-otlp-proto-http-1.25.0 opentelemetry-proto-1.25.0 opentelemetry-sdk-1.25.0 opentelemetry-semantic-conventions-0.46b0 orjson-3.10.5 packaging-23.2 pymongo-4.7.2 pyreqwest-impersonate-0.4.8 python-dotenv-1.0.0 regex-2023.12.25 tiktoken-0.5.2 typer-0.9.4 typing-inspect-0.9.0\n"
          ]
        }
      ],
      "source": [
        "pip install pymongo==4.7.2 crewai==0.22.5 langchain==0.1.10 langchain-community langchain-openai==0.0.5 duckduckgo-search==6.1.5"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {
        "id": "chmicvLP7T46"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "import pprint\n",
        "\n",
        "import pymongo\n",
        "\n",
        "# MongoDB Setup\n",
        "MDB_URI = \"mongodb+srv://<user>:<password>@cluster0.abc123.mongodb.net/\"\n",
        "client = pymongo.MongoClient(MDB_URI, appname=\"devrel.showcase.crewai\")\n",
        "db = client[\"sample_analytics\"]\n",
        "collection = db[\"transactions\"]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {
        "id": "PSRcCM6y7X8H"
      },
      "outputs": [],
      "source": [
        "# Azure OpenAI Setup\n",
        "from langchain_openai import AzureChatOpenAI\n",
        "\n",
        "AZURE_OPENAI_ENDPOINT = \"https://__DEMO__.openai.azure.com\"\n",
        "AZURE_OPENAI_API_KEY = \"__AZURE_OPENAI_API_KEY__\"\n",
        "deployment_name = \"gpt-4-32k\"  # The name of your model deployment\n",
        "default_llm = AzureChatOpenAI(\n",
        "    openai_api_version=os.environ.get(\"AZURE_OPENAI_VERSION\", \"2023-07-01-preview\"),\n",
        "    azure_deployment=deployment_name,\n",
        "    azure_endpoint=AZURE_OPENAI_ENDPOINT,\n",
        "    api_key=AZURE_OPENAI_API_KEY,\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "metadata": {
        "id": "UIkkX2_D7bf-"
      },
      "outputs": [],
      "source": [
        "# Web Search Setup\n",
        "from langchain.tools import tool\n",
        "from langchain_community.tools import DuckDuckGoSearchResults\n",
        "\n",
        "duck_duck_go = DuckDuckGoSearchResults(backend=\"news\", max_results=10)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {
        "id": "f5Bb7eFX7glD"
      },
      "outputs": [],
      "source": [
        "# Search Tool - Web Search\n",
        "@tool\n",
        "def search_tool(query: str):\n",
        "    \"\"\"\n",
        "    Perform online research on a particular stock.\n",
        "    Will return search results along with snippets of each result.\n",
        "    \"\"\"\n",
        "    print(\"\\n\\nSearching DuckDuckGo for:\", query)\n",
        "    search_results = duck_duck_go.run(query)\n",
        "    search_results_str = \"[recent news for: \" + query + \"]\\n\" + str(search_results)\n",
        "    return search_results_str"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "metadata": {
        "id": "rPFRsps27l0G"
      },
      "outputs": [],
      "source": [
        "# Research Agent Setup\n",
        "from crewai import Agent, Crew, Process, Task\n",
        "\n",
        "AGENT_ROLE = \"Investment Researcher\"\n",
        "AGENT_GOAL = \"\"\"\n",
        "  Research stock market trends, company news, and analyst reports to identify potential investment opportunities.\n",
        "\"\"\"\n",
        "researcher = Agent(\n",
        "    role=AGENT_ROLE,\n",
        "    goal=AGENT_GOAL,\n",
        "    verbose=True,\n",
        "    llm=default_llm,\n",
        "    backstory=\"Expert stock researcher with decades of experience.\",\n",
        "    tools=[search_tool],\n",
        ")\n",
        "\n",
        "task1 = Task(\n",
        "    description=\"\"\"\n",
        "Using the following information:\n",
        "\n",
        "[VERIFIED DATA]\n",
        "{agg_data}\n",
        "\n",
        "*note*\n",
        "The data represents the net gain or loss of each stock symbol for each transaction type (buy/sell).\n",
        "Net gain or loss is a crucial metric used to gauge the profitability or efficiency of an investment.\n",
        "It's computed by subtracting the total buy value from the total sell value for each stock.\n",
        "[END VERIFIED DATA]\n",
        "\n",
        "[TASK]\n",
        "- Generate a detailed financial report of the VERIFIED DATA.\n",
        "- Research current events and trends, and provide actionable insights and recommendations.\n",
        "\n",
        "\n",
        "[report criteria]\n",
        "  - Use all available information to prepare this final financial report\n",
        "  - Include a TLDR summary\n",
        "  - Include 'Actionable Insights'\n",
        "  - Include 'Strategic Recommendations'\n",
        "  - Include a 'Other Observations' section\n",
        "  - Include a 'Conclusion' section\n",
        "  - IMPORTANT! You are a friendly and helpful financial expert. Always provide the best possible answer using the available information.\n",
        "[end report criteria]\n",
        "  \"\"\",\n",
        "    agent=researcher,\n",
        "    expected_output=\"concise markdown financial summary of the verified data and list of key points and insights from researching current events\",\n",
        "    tools=[search_tool],\n",
        ")\n",
        "# Crew Creation\n",
        "tech_crew = Crew(agents=[researcher], tasks=[task1], process=Process.sequential)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Q-0j6AO17qZH",
        "outputId": "30d5c32e-a758-42f6-e12c-23193962b935"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "MongoDB Aggregation Pipeline Results:\n",
            "[{'netGain': 72769230.71428967, 'symbol': 'amzn'},\n",
            " {'netGain': 39912931.04990542, 'symbol': 'sap'},\n",
            " {'netGain': 25738882.292086124, 'symbol': 'aapl'}]\n"
          ]
        }
      ],
      "source": [
        "# MongoDB Aggregation Pipeline\n",
        "pipeline = [\n",
        "    {\n",
        "        \"$unwind\": \"$transactions\"  # Deconstruct the transactions array into separate documents\n",
        "    },\n",
        "    {\n",
        "        \"$group\": {  # Group documents by stock symbol\n",
        "            \"_id\": \"$transactions.symbol\",  # Use symbol as the grouping key\n",
        "            \"buyValue\": {  # Calculate total buy value\n",
        "                \"$sum\": {\n",
        "                    \"$cond\": [  # Conditional sum based on transaction type\n",
        "                        {\n",
        "                            \"$eq\": [\"$transactions.transaction_code\", \"buy\"]\n",
        "                        },  # Check for \"buy\" transactions\n",
        "                        {\n",
        "                            \"$toDouble\": \"$transactions.total\"\n",
        "                        },  # Convert total to double for sum\n",
        "                        0,  # Default value for non-buy transactions\n",
        "                    ]\n",
        "                }\n",
        "            },\n",
        "            \"sellValue\": {  # Calculate total sell value (similar to buyValue)\n",
        "                \"$sum\": {\n",
        "                    \"$cond\": [\n",
        "                        {\"$eq\": [\"$transactions.transaction_code\", \"sell\"]},\n",
        "                        {\"$toDouble\": \"$transactions.total\"},\n",
        "                        0,\n",
        "                    ]\n",
        "                }\n",
        "            },\n",
        "        }\n",
        "    },\n",
        "    {\n",
        "        \"$project\": {  # Project desired fields (renaming and calculating net gain)\n",
        "            \"_id\": 0,  # Exclude original _id field\n",
        "            \"symbol\": \"$_id\",  # Rename _id to symbol for clarity\n",
        "            \"netGain\": {\"$subtract\": [\"$sellValue\", \"$buyValue\"]},  # Calculate net gain\n",
        "        }\n",
        "    },\n",
        "    {\n",
        "        \"$sort\": {\"netGain\": -1}  # Sort results by net gain (descending)\n",
        "    },\n",
        "    {\"$limit\": 3},  # Limit results to top 3 stocks\n",
        "]\n",
        "results = list(collection.aggregate(pipeline))\n",
        "client.close()\n",
        "\n",
        "# Print MongoDB Aggregation Pipeline Results\n",
        "print(\"MongoDB Aggregation Pipeline Results:\")\n",
        "\n",
        "pprint.pprint(\n",
        "    results\n",
        ")  # pprint is used to  to “pretty-print” arbitrary Python data structures"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "PFsZuTRk7ugA",
        "outputId": "888ecd1c-b6d1-433f-8a9b-8e46f6ee230e"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\n",
            "\n",
            "\u001b[1m> Entering new CrewAgentExecutor chain...\u001b[0m\n",
            "\u001b[32;1m\u001b[1;3mGiven the net gain data of the stocks, the first step would be to analyze the performance of each stock. This can be done by comparing the net gain of each stock. The next step would be to research recent news and trends about these stocks to provide actionable insights and recommendations. Let's start by researching each stock separately. \n",
            "\n",
            "Action: search_tool\n",
            "Action Input: {\"query\": \"amzn stock news\"}\u001b[0m\n",
            "\n",
            "Searching DuckDuckGo for: amzn stock news\n",
            "\u001b[93m \n",
            "\n",
            "[recent news for: amzn stock news]\n",
            "[snippet: Jeff Bezos' Amazon is one of the true-blue Silicon Valley Magnificent 7 stocks, a 30-year-old company dating all the way back to 1994. And just like all the other Magnificent 7 stocks, it's had an interesting 2024 so far., title: Amazon (AMZN) stock price to reach over $300? 2030 predictions, link: https://www.msn.com/en-us/money/markets/amazon-amzn-stock-price-to-reach-over-300-2030-predictions/ar-BB1oqmvu, date: 2024-06-18T08:14:55+00:00, source: invezz on MSN.com], [snippet: In recent years, the e-commerce scene has battled macro headwinds and rapidly changing consumer behavior. Undoubtedly, high rates and fears of, title: PDD, AMZN, MELI: Which E-Commerce Stock Is the Strongest Buy?, link: https://markets.businessinsider.com/news/stocks/pdd-amzn-meli-which-e-commerce-stock-is-the-strongest-buy-1033485332, date: 2024-06-17T20:34:00+00:00, source: Business Insider], [snippet: Amazon.com is primed for a payout, two investment pros believe. Knowing how companies use cash have helped them beat the market., title: Cheap bonds and stock yield are helping these 2 income-fund managers beat the market, link: https://www.msn.com/en-us/money/savingandinvesting/cheap-bonds-and-stock-yield-are-helping-these-2-income-fund-managers-beat-the-market/ar-BB1one3f, date: 2024-06-18T21:38:00+00:00, source: MarketWatch on MSN.com], [snippet: The TSMC Trade: The ARK Next Generation Internet ETF ARKW fund bought 30094 shares of Taiwan Semiconductor Manufacturing Company. The transaction was valued at $5.33 million. TSMC stock closed 2.7% higher at $177.24 in Monday's regular session., title: Cathie Wood-Led Ark Picks Up $5.3M Worth Of TSMC Shares— Also Picks Up Palantir, Amazon Stock Amid Ongoing AI Frenzy, link: https://www.msn.com/en-us/money/news/cathie-wood-led-ark-picks-up-5-3m-worth-of-tsmc-shares-also-picks-up-palantir-amazon-stock-amid-ongoing-ai-frenzy/ar-BB1opGt7, date: 2024-06-18T03:55:11+00:00, source: Benzinga on MSN.com]\n",
            "\u001b[00m\n",
            "\u001b[32;1m\u001b[1;3mThought: \n",
            "The recent news for Amazon (AMZN) stock indicates that the company is still a strong player in the e-commerce scene, despite facing macro headwinds and changing consumer behavior. There are also predictions that the stock price might reach over $300 by 2030. This suggests that the AMZN stock could have a potential for long-term growth. Let's proceed to research the SAP stock.\n",
            "\n",
            "Action: search_tool\n",
            "Action Input: {\"query\": \"sap stock news\"}\u001b[0m\n",
            "\n",
            "Searching DuckDuckGo for: sap stock news\n",
            "\u001b[93m \n",
            "\n",
            "[recent news for: sap stock news]\n",
            "[snippet: WalkMe (NASDAQ:WKME) skyrocketed in trading after it was announced that the software-as-a-service (SaaS) company will be acquired by SAP SE, title: M&A News: WalkMe Skyrockets on Acquisition By SAP (NYSE:SAP) for $1.5B, link: https://www.msn.com/en-us/money/markets/m-a-news-walkme-skyrockets-on-acquisition-by-sap-nysesap-for-15b/ar-BB1nHoJE, date: 2024-06-05T16:32:59+00:00, source: TipRanks on MSN.com], [snippet: German software giant SAP has agreed to buy WalkMe in an all-cash deal valued at about $1.5 billion. The acquisition of WalkMe, a digital adoption platform operator that works with organizations on needs like improving productivity and lowering risk,, title: Software giant SAP agrees to buy WalkMe for $1.5 billion cash, link: https://www.msn.com/en-us/money/companies/software-giant-sap-agrees-to-buy-walkme-for-15-billion-cash/ar-BB1nGknI, date: 2024-06-05T14:47:16+00:00, source: The Associated Press on MSN.com], [snippet: SAP SE announced on Wednesday its acquisition of WalkMe, a leading digital adoption platform, in a cash transaction valued at approximately $1.5 billion., title: Breaking: SAP buys WalkMe in $1.5 billion cash deal, boosting digital adoption capabilities, link: https://invezz.com/news/2024/06/05/breaking-sap-buys-walkme-in-1-5-billion-cash-deal-boosting-digital-adoption-capabilities/, date: 2024-06-05T11:11:00+00:00, source: Invezz], [snippet: German enterprise software company SAP SE said Wednesday it has agreed to acquire WalkMe Ltd. in an all-cash deal valued at about $1.5 billion., title: SAP to acquire WalkMe in all-cash deal valued at about $1.5 billion, link: https://www.msn.com/en-us/money/companies/sap-to-acquire-walkme-in-all-cash-deal-valued-at-about-15-billion/ar-BB1nFiao, date: 2024-06-05T10:38:00+00:00, source: MarketWatch on MSN.com]\n",
            "\u001b[00m\n",
            "\u001b[32;1m\u001b[1;3mThought: \n",
            "The recent news about SAP stock indicates that the company is expanding its portfolio through acquisitions. SAP recently acquired WalkMe, a leading digital adoption platform, in an all-cash deal valued at approximately $1.5 billion. This acquisition could potentially boost SAP's capabilities in the digital adoption field. Now, let's research Apple (AAPL) stock.\n",
            "\n",
            "Action: search_tool\n",
            "Action Input: {\"query\": \"aapl stock news\"}\u001b[0m\n",
            "\n",
            "Searching DuckDuckGo for: aapl stock news\n",
            "\u001b[93m \n",
            "\n",
            "[recent news for: aapl stock news]\n",
            "[snippet: Apple (NASDAQ:AAPL) stock certainly has multiple, positive catalysts going forward. The most important of these drivers are:    The artificial intelligence (AI) enhancements it just introduced.    The iPhone's revitalization in China., title: There Are Better Picks to Enjoy the Fruits of AI Than Apple Stock, link: https://www.msn.com/en-us/money/markets/there-are-better-picks-to-enjoy-the-fruits-of-ai-than-apple-stock/ar-BB1ossCC, date: 2024-06-18T18:24:18+00:00, source: Investorplace News on MSN.com], [snippet: Phone maker Apple (NASDAQ:AAPL) has announced a strategic shift in its financial services offerings by discontinuing its Apple Pay Later program., title: Apple (AAPL) Shifts Focus, Discontinues Apple Pay Later, link: https://www.msn.com/en-us/news/technology/apple-aapl-shifts-focus-discontinues-apple-pay-later/ar-BB1oqmZ9, date: 2024-06-18T05:50:56+00:00, source: TipRanks on MSN.com], [snippet: Apple (NASDAQ:AAPL) has been one of the most remarkable investment success ... An interesting aspect of Corning's investment case is that the stock could be a compelling dividend growth pick. The company has already increased its dividend for 13 ..., title: AAPL Picking: 3 Stocks to Buy Because of Their Apple Partnerships, link: https://markets.businessinsider.com/news/stocks/aapl-picking-3-stocks-to-buy-because-of-their-apple-partnerships-1033486442, date: 2024-06-18T04:20:00+00:00, source: Business Insider], [snippet: One of America's largest technology-focused ETFs will likely be forced to buy billions of dollars worth of Nvidia stock when it rebalances Friday, a byproduct of both the chip giant's meteoric rise and arcane fund diversification rules., title: Why a $70B Fund Will Likely Load Up on Nvidia Stock, Dump Apple This Week, link: https://www.msn.com/en-us/money/other/why-a-70b-fund-will-likely-load-up-on-nvidia-stock-dump-apple-this-week/ar-BB1osCb6, date: 2024-06-18T18:25:14+00:00, source: Investopedia on MSN.com]\n",
            "\u001b[00m\n",
            "\u001b[32;1m\u001b[1;3mThought: \n",
            "Recent news about Apple (AAPL) stock suggests that the company has multiple positive catalysts, such as the artificial intelligence (AI) enhancements it introduced recently and the revitalization of the iPhone in China. However, there is news that a large technology-focused ETF might dump Apple stocks in favor of Nvidia, which could potentially cause a decline in the AAPL stock price. Now that we have gathered all the required information, let's prepare the financial report. \n",
            "\n",
            "Final Answer: \n",
            "\n",
            "# Financial Report\n",
            "\n",
            "## TLDR Summary\n",
            "\n",
            "- Amazon (AMZN) has the highest net gain among the three stocks, with a net gain of $72,769,230.71. The company remains a strong player in the e-commerce scene. Predictions suggest that the stock price might reach over $300 by 2030.\n",
            "- SAP has the second highest net gain with $39,912,931.04. The company recently acquired WalkMe, which could potentially boost its capabilities in the digital adoption field.\n",
            "- Apple (AAPL) has the lowest net gain among the three stocks, with a net gain of $25,738,882.29. Despite multiple positive catalysts, recent news indicates potential decline in the AAPL stock price due to a shift in ETF investments.\n",
            "\n",
            "## Actionable Insights\n",
            "\n",
            "- The predicted long-term growth of Amazon's stock price suggests investors can consider AMZN for long-term investments.\n",
            "- SAP's recent acquisition of WalkMe may enhance its offerings, making it a potential investment for those interested in digital adoption platforms.\n",
            "- Apple's future stock performance might be affected due to changes in ETF investments. Investors should keep a close eye on AAPL stock.\n",
            "\n",
            "## Strategic Recommendations\n",
            "\n",
            "- Given the predicted long-term growth of AMZN, investors can consider increasing their holdings in AMZN.\n",
            "- Investors interested in digital adoption platforms can consider investing in SAP due to its recent acquisition of WalkMe.\n",
            "- Due to the potential decline in AAPL stock price, investors might want to reevaluate their holdings in AAPL.\n",
            "\n",
            "## Other Observations\n",
            "\n",
            "- All three companies are making strategic decisions that could potentially affect their future stock performance. Continuing to monitor news and trends about these companies will help in making informed investment decisions.\n",
            "\n",
            "## Conclusion\n",
            "\n",
            "The stocks of Amazon, SAP, and Apple show different potentials based on their recent news and net gains. Each stock presents unique opportunities and challenges. Investors should align their investment strategies with the trends and events surrounding these stocks.\u001b[0m\n",
            "\n",
            "\u001b[1m> Finished chain.\u001b[0m\n"
          ]
        },
        {
          "data": {
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            },
            "text/plain": [
              "\"# Financial Report\\n\\n## TLDR Summary\\n\\n- Amazon (AMZN) has the highest net gain among the three stocks, with a net gain of $72,769,230.71. The company remains a strong player in the e-commerce scene. Predictions suggest that the stock price might reach over $300 by 2030.\\n- SAP has the second highest net gain with $39,912,931.04. The company recently acquired WalkMe, which could potentially boost its capabilities in the digital adoption field.\\n- Apple (AAPL) has the lowest net gain among the three stocks, with a net gain of $25,738,882.29. Despite multiple positive catalysts, recent news indicates potential decline in the AAPL stock price due to a shift in ETF investments.\\n\\n## Actionable Insights\\n\\n- The predicted long-term growth of Amazon's stock price suggests investors can consider AMZN for long-term investments.\\n- SAP's recent acquisition of WalkMe may enhance its offerings, making it a potential investment for those interested in digital adoption platforms.\\n- Apple's future stock performance might be affected due to changes in ETF investments. Investors should keep a close eye on AAPL stock.\\n\\n## Strategic Recommendations\\n\\n- Given the predicted long-term growth of AMZN, investors can consider increasing their holdings in AMZN.\\n- Investors interested in digital adoption platforms can consider investing in SAP due to its recent acquisition of WalkMe.\\n- Due to the potential decline in AAPL stock price, investors might want to reevaluate their holdings in AAPL.\\n\\n## Other Observations\\n\\n- All three companies are making strategic decisions that could potentially affect their future stock performance. Continuing to monitor news and trends about these companies will help in making informed investment decisions.\\n\\n## Conclusion\\n\\nThe stocks of Amazon, SAP, and Apple show different potentials based on their recent news and net gains. Each stock presents unique opportunities and challenges. Investors should align their investment strategies with the trends and events surrounding these stocks.\""
            ]
          },
          "execution_count": 13,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "# Start the task execution\n",
        "tech_crew.kickoff(inputs={\"agg_data\": str(results)})"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    },
    "widgets": {
      "application/vnd.jupyter.widget-state+json": {
        "state": {}
      }
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
